package com.china08.yxyapi.service.manage.tec.teaching.homework.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtController.ArticleModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtController.ClassModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtController.QuesModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtController.ReqModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtController.StudentModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtV2Controller.ArticleModelV2;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtV2Controller.ClassModelV2;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtV2Controller.QuesModelV2;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtV2Controller.ReqModelV2;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesCrtV2Controller.StudentModelV2;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesPreviewController.KnowModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.workassign.WorkAssignQuesPreviewController.QuesReqModel;
import com.china08.yxyapi.entity.db.yxy.YxyQuesKnow;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.homework.HomeWorkQuesUsed;
import com.china08.yxyapi.entity.mg.homework.HomeworkTask;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskClass;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues.Article;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.repository.db.YxyQuesKnowRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkQuesUsedRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskClassRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.ElasticQuesService;
import com.china08.yxyapi.service.manage.tec.teaching.homework.WorkAssignService;

@Service
public class WorkAssignServiceImpl implements WorkAssignService {

    private final static Logger LOGGER = LoggerFactory.getLogger(WorkAssignServiceImpl.class);

    @Autowired
    private HomeworkTaskRepository taskRepository;

    @Autowired
    private HomeworkTaskClassRepository taskClassRepository;

    @Autowired
    private HomeworkTaskQuesRepository taskQuesRepository;

    @Autowired
    private HomeworkTaskReportRepository taskReportRepository;

    @Autowired
    private ElasticQuesService elasticService;

    @Autowired
    private YxyQuesKnowRepository qKnowRepository;

    @Autowired
    private HomeworkQuesUsedRepository quesUsedRepository;

    @Override
    @Transactional
    public void sendHomeWork(ReqModel reqModel, String schoolId, String userId, String userNick) throws ParseException {

        LOGGER.info("开始发布作业");
        Long start = System.currentTimeMillis();
        // Date curreDate = new Date();

        // 开始时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        Date startDate = null;
        Integer type1 = reqModel.type1;
        if (type1 == 2) {
            startDate = new Date();
        } else {
            if (StringUtils.isNotBlank(reqModel.startDate)) {
                reqModel.startDate = reqModel.startDate.replace("Z", " UTC");
                startDate = sdf.parse(reqModel.startDate);
            }

        }

        // 结束时间
        Integer type2 = reqModel.type2;
        Date endDate = null;
        if (type2 != null && type2 == 3) {
            endDate = getTimesnight();
        } else if (type2 != null && type2 == 6) {
            endDate = getTimesNextnight();
        } else if (type2 != null && type2 == 9) {
            endDate = getTimesWeeknight();
        } else {
            if (StringUtils.isNotBlank(reqModel.endDate)) {
                reqModel.endDate = reqModel.endDate.replace("Z", " UTC");
                endDate = sdf.parse(reqModel.endDate);
            }
        }

        // Assert.isTrue(curreDate.getTime() < startDate.getTime(),
        // "开始时间不能小于当前时间");
        Assert.isTrue(startDate.getTime() < endDate.getTime(), "截止时间不能小于开始时间");
        // Assert.isTrue(curreDate.getTime() < endDate.getTime(),
        // "截止时间不能小于当前时间");

        // 作业类型
        String content = reqModel.content;
        List<String> quesIdList = new ArrayList<String>();
        reqModel.quesIdList.forEach(quesModel -> {
            quesIdList.add(quesModel.quesId);
        });
        // 转化题的Javabean为map
        Map<String, List<Integer>> quesMap = convertQuesToMap(reqModel.quesIdList);

        String taskType = "";
        if (StringUtils.isNotBlank(content) && CollectionUtils.isNotEmpty(quesIdList)) {
            taskType = "2";
        } else if (StringUtils.isBlank(content) && CollectionUtils.isNotEmpty(quesIdList)) {
            taskType = "0";
        } else if (StringUtils.isNotBlank(content) && CollectionUtils.isEmpty(quesIdList)) {
            taskType = "1";
        }

        HomeworkTask task = new HomeworkTask();
        List<ClassModel> classModelList = reqModel.classModelList;
        List<String> classIdList = new ArrayList<String>();
        for (ClassModel classReqModel : classModelList) {
            String classId = classReqModel.classId;
            classIdList.add(classId);
        }
        String stage = reqModel.stage;
        String subject = reqModel.subject;
        String subjectName = reqModel.subjectName;
        task.setTitle(reqModel.title);
        task.setSubTitle(reqModel.subTitle);
        task.setSchoolId(schoolId);
        task.setPublishUserId(userId);
        task.setPublishUserNick(userNick);
        task.setStage(stage);
        task.setSubject(subject);
        task.setSubjectName(subjectName);
        task.setPublishAnswer(reqModel.publishAnswer);
        task.setPublishDate(startDate);
        task.setClassIds(classIdList);
        task.setPredictDate(endDate);
        task.setKnowIds(reqModel.knowIdList);
        task.setKnowNames(reqModel.knowNameList);
        task.setTaskType(taskType);
        task.setIfNeedSumbit(reqModel.ifNeedSumbit);
        task.setSource(0);
        task = taskRepository.save(task);

        List<HomeworkTaskClass> taskClassList = new ArrayList<HomeworkTaskClass>();
        HomeworkTaskClass taskClass = null;
        for (ClassModel classReqModel : classModelList) {
            taskClass = new HomeworkTaskClass();
            taskClass.setTitle(task.getTitle());
            taskClass.setSubTitle(task.getSubTitle());
            taskClass.setClassId(classReqModel.classId);
            taskClass.setClassName(classReqModel.classNick);
            taskClass.setNumOfStudent(classReqModel.studentNum);
            taskClass.setGrade(classReqModel.grade);
            taskClass.setTaskId(task.getId());
            taskClass.setSchoolId(schoolId);
            taskClass.setStage(task.getStage());
            taskClass.setSubject(task.getSubject());
            taskClass.setSubjectName(task.getSubjectName());
            taskClass.setPublishDate(task.getPublishDate());
            taskClass.setPredictDate(task.getPredictDate());
            taskClass.setPublishUserId(task.getPublishUserId());
            taskClass.setPublishUserNick(task.getPublishUserNick());
            taskClass.setTaskType(task.getTaskType());
            taskClass.setSource(0);
            taskClassList.add(taskClass);
        }
        taskClassRepository.save(taskClassList);

        // 试题类作业
        HomeworkTaskQues taskQues = null;
        HomeWorkQuesUsed quesUsed = null;
        List<HomeworkTaskQues> taskQuesList = new ArrayList<HomeworkTaskQues>();
        List<HomeWorkQuesUsed> quesUsedList = new ArrayList<HomeWorkQuesUsed>();
        int i = 1;
        for (String quesId : quesIdList) {
            quesUsed = quesUsedRepository.findByQuesId(quesId);
            if (quesUsed != null) {
                quesUsed.setUsedCount(quesUsed.getUsedCount() + 1);
            } else {
                quesUsed = new HomeWorkQuesUsed();
                quesUsed.setQuesId(quesId);
                quesUsed.setUsedCount(1l);
            }
            quesUsedList.add(quesUsed);
            // 查询试题
            ElasticYxyYxyQuesResource eQues = elasticService.findByEsQuesId(quesId);
            taskQues = new HomeworkTaskQues();
            taskQues.setTitle(task.getTitle());
            taskQues.setSubTitle(task.getSubTitle());
            taskQues.setTaskId(task.getId());
            taskQues.setPredictDate(task.getPredictDate());
            taskQues.setQuesId(quesId);
            taskQues.setTeacherId(userId);
            taskQues.setStage(reqModel.stage);
            taskQues.setSubject(reqModel.subject);
            taskQues.setOrder(i++);
            taskQues.setSource(0);
            // 题的知识点
            List<Integer> knowIds = quesMap.get(quesId);
            taskQues.setKnowId(knowIds);// 知识点id
            // 题的知识点名称
            List<YxyQuesKnow> quesKnows = qKnowRepository.findByIdIn(knowIds);
            List<String> knowTextsList = new ArrayList<String>();
            quesKnows.forEach(quesKnow -> {
                knowTextsList.add(quesKnow.getName());
            });
            taskQues.setKnowName(knowTextsList);
            taskQues.setDifficultyLevel(Integer.parseInt(eQues.getDifficultyLevel()));// 难度级别
            taskQues.setDifficultyXs(eQues.getDifficultyXishu());// 难度系数
            taskQues.setTaskType(task.getTaskType());
            String questionType = eQues.getQuestionType();
            if (StringUtils.equals(questionType, "1")) {
                taskQues.setQuesType("0");
            } else if (StringUtils.equals(questionType, "8")) {
                taskQues.setQuesType("1");
            } else if (StringUtils.equals(questionType, "2")) {
                taskQues.setQuesType("3");
            } else {
                taskQues.setQuesType("4");
            }
            taskQuesList.add(taskQues);
        }
        quesUsedRepository.save(quesUsedList);

        // 通知类作业
        if (StringUtils.isNotBlank(content)) {
            taskQues = new HomeworkTaskQues();
            taskQues.setTitle(task.getTitle());
            taskQues.setSubTitle(task.getSubTitle());
            taskQues.setTaskId(task.getId());
            taskQues.setPredictDate(task.getPredictDate());
            taskQues.setQuesId("tz" + UUID.randomUUID());// 生成通知类试题id
            taskQues.setQuesContent(content);
            taskQues.setQuesImage(reqModel.quesImages);
            // 通知类试题的文档
            List<Article> quesArticleList = new ArrayList<Article>();
            Article article = null;
            for (ArticleModel articleReqModel : reqModel.quesArticles) {
                article = new Article();
                article.setArticle_name(articleReqModel.docName);
                article.setUrl(articleReqModel.docUrl);
                quesArticleList.add(article);
            }
            taskQues.setQuesType("2");
            taskQues.setQuesArticle(quesArticleList);
            taskQues.setTeacherId(userId);
            taskQues.setStage(stage);
            taskQues.setSubject(subject);
            int order1 = 1;
            if (CollectionUtils.isNotEmpty(reqModel.quesIdList)) {
                order1 = reqModel.quesIdList.size() + 1;
            }
            taskQues.setOrder(order1);// 通知类试题序号
            taskQues.setTaskType(task.getTaskType());
            // 通知类作业是否需要在线提交
            taskQues.setIfNeedSumbit(reqModel.ifNeedSumbit);
            taskQues.setSource(0);
            taskQuesList.add(taskQues);
        }
        taskQuesRepository.save(taskQuesList);

        List<HomeworkTaskReport> taskReportList = new ArrayList<HomeworkTaskReport>();
        HomeworkTaskReport taskReport = null;

        // 年度
        LocalDate localDate = LocalDate.now();
        String annual = null;
        if (localDate.getMonthValue() < 9) {
            annual = (localDate.getYear() - 1) + "";
        } else {
            annual = localDate.getYear() + "";
        }
        for (ClassModel classReqModel : classModelList) {
            List<StudentModel> studentModelList = classReqModel.studentModelList;
            for (StudentModel srudentModel : studentModelList) {
                taskReport = new HomeworkTaskReport();
                taskReport.setTaskId(task.getId());
                taskReport.setTitle(task.getTitle());
                taskReport.setSubTitle(task.getSubTitle());
                taskReport.setStudentId(srudentModel.studentId);
                taskReport.setStudentNick(srudentModel.studentName);
                // 学生默认头像
                // String avaString =
                // StringUtils.defaultIfBlank(srudentModel.avatar, "默认头像链接");
                taskReport.setAvatar(srudentModel.avatar);
                taskReport.setSchoolId(schoolId);
                taskReport.setClassId(classReqModel.classId);
                taskReport.setClassName(classReqModel.classNick);
                taskReport.setGrade(classReqModel.grade);
                taskReport.setAnnual(annual);
                taskReport.setStage(stage);
                taskReport.setSubject(subject);
                taskReport.setSubjectName(subjectName);
                taskReport.setPredictDate(task.getPredictDate());
                taskReport.setPublishAnswer(task.getPublishAnswer());
                taskReport.setTaskType(task.getTaskType());
                taskReport.setPublishDate(task.getPublishDate());
                taskReport.setSource(0);
                taskReportList.add(taskReport);
            }
        }
        taskReportRepository.save(taskReportList);
        LOGGER.info("发布完成共用时:" + ((System.currentTimeMillis() - start) / 1000) + "s");
    }

    // 获得当天24点时间
    public static Date getTimesnight() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    // 获得本周日24点时间
    public static Date getTimesWeeknight() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getTimesWeekmorning());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        return cal.getTime();
    }

    // 获得本周一0点时间
    public static Date getTimesWeekmorning() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return cal.getTime();
    }

    // 获得明天24点时间
    public static Date getTimesNextnight() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getTimesnight());
        cal.add(Calendar.DATE, 1);
        return cal.getTime();
    }

    @Override
    public List<KnowModel> findKnowModelList(List<ElasticYxyYxyQuesResource> quesList) {
        Integer max = 0;
        List<Integer> knowIdList = findKnowIdList(quesList);
        List<KnowModel> knowModelList = new ArrayList<KnowModel>();
        KnowModel knowModel = null;
        for (Integer integer : knowIdList) {
            Integer quesCount = 0;
            for (ElasticYxyYxyQuesResource eQues : quesList) {
                if (eQues.getKnowledgeIds().contains(integer)) {
                    quesCount++;
                }
            }
            knowModel = new KnowModel();
            knowModel.knowId = integer;
            YxyQuesKnow quesKnow = qKnowRepository.findOne(integer);
            knowModel.knowName = quesKnow.getName();
            knowModel.quesCount = quesCount;

            knowModelList.add(knowModel);
        }
        knowModelList.sort((KnowModel h1, KnowModel h2) -> h2.quesCount.compareTo(h1.quesCount));

        // 排序蓝色区域
        if (CollectionUtils.isNotEmpty(knowModelList)) {
            max = knowModelList.get(0).quesCount;
        }

        List<KnowModel> knowModelList2 = new ArrayList<KnowModel>();
        for (KnowModel knowModel2 : knowModelList) {
            Integer quesCount = knowModel2.quesCount;
            float percent = ((float) quesCount / (float) max) * 100;
            BigDecimal mData = new BigDecimal(percent).setScale(0, BigDecimal.ROUND_HALF_UP);
            knowModel2.percent = mData.intValue();
            knowModelList2.add(knowModel2);
        }
        return knowModelList2;
    }

    @Override
    public Map<String, Integer> findDifficultStatic(List<ElasticYxyYxyQuesResource> quesList) {
        // 难度统计
        // 1 易 2 中 3 难
        Map<String, Integer> map = new HashMap<String, Integer>();
        int a = 0;
        int b = 0;
        int c = 0;
        for (ElasticYxyYxyQuesResource eQues : quesList) {
            Integer difficultLevlel = Integer.parseInt(eQues.getDifficultyLevel());
            if (difficultLevlel == 1) {
                a++;
            } else if (difficultLevlel == 2) {
                b++;
            } else if (difficultLevlel == 3) {
                c++;
            }
        }
        map.put("easy", a);
        map.put("middle", b);
        map.put("difficult", c);
        return map;
    }

    // 查询题下的所有的知识点id
    @Override
    public List<Integer> findKnowIdList(List<ElasticYxyYxyQuesResource> quesList) {
        List<Integer> knowIdList = new ArrayList<Integer>();
        for (ElasticYxyYxyQuesResource eQues : quesList) {
            knowIdList.addAll(eQues.getKnowledgeIds());
        }

        List<Integer> knowIdList2 = new ArrayList<>();
        knowIdList.stream().forEach(p -> {
            if (!knowIdList2.contains(p)) {
                knowIdList2.add(p);
            }
        });
        return knowIdList2;
    }

    /**
     * 生成试题的知识点统计
     */
    @Override
    public List<KnowModel> findKnowModelList2(List<QuesReqModel> quesList) {
        Integer max = 0;
        List<Integer> knowIdList = findKnowIdList2(quesList);
        List<KnowModel> knowModelList = new ArrayList<KnowModel>();
        KnowModel knowModel = null;
        for (Integer integer : knowIdList) {
            Integer quesCount = 0;
            for (QuesReqModel eQues : quesList) {
                if (eQues.know.contains(integer)) {
                    quesCount++;
                }
            }
            knowModel = new KnowModel();
            knowModel.knowId = integer;
            YxyQuesKnow quesKnow = qKnowRepository.findOne(integer);
            knowModel.knowName = quesKnow.getName();
            knowModel.quesCount = quesCount;
            knowModelList.add(knowModel);
        }
        knowModelList.sort((KnowModel h1, KnowModel h2) -> h2.quesCount.compareTo(h1.quesCount));

        // 排序蓝色区域
        if (CollectionUtils.isNotEmpty(knowModelList)) {
            max = knowModelList.get(0).quesCount;
        }

        List<KnowModel> knowModelList2 = new ArrayList<KnowModel>();
        for (KnowModel knowModel2 : knowModelList) {
            Integer quesCount = knowModel2.quesCount;
            float percent = ((float) quesCount / (float) max) * 100;
            BigDecimal mData = new BigDecimal(percent).setScale(0, BigDecimal.ROUND_HALF_UP);
            knowModel2.percent = mData.intValue();
            knowModelList2.add(knowModel2);
        }
        return knowModelList2;
    }

    /**
     * 获取本次作业所涉及所有知识点
     */
    @Override
    public List<Integer> findKnowIdList2(List<QuesReqModel> quesList) {
        List<Integer> knowIdList = new ArrayList<Integer>();
        for (QuesReqModel quesReqModel : quesList) {
            knowIdList.addAll(quesReqModel.know);
        }

        List<Integer> knowIdList2 = new ArrayList<>();
        knowIdList.stream().forEach(p -> {
            if (!knowIdList2.contains(p)) {
                knowIdList2.add(p);
            }
        });
        return knowIdList2;
    }

    /**
     * 转化题的请求信息为map
     */
    private Map<String, List<Integer>> convertQuesToMap(List<QuesModel> quesIdList) {
        Map<String, List<Integer>> quesMap = new HashMap<String, List<Integer>>();
        quesIdList.forEach(ques -> {
            quesMap.put(ques.quesId, ques.know);
        });
        return quesMap;
    }

    @Override
    public HomeworkTask sendHomeWorkV2(ReqModelV2 reqModel, String schoolId, String userId, String userNick)
            throws ParseException {
        LOGGER.info("开始发布作业");
        Long start = System.currentTimeMillis();

        // 开始时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        Date startDate = null;
        Integer type1 = reqModel.type1;
        if (type1 == 2) {
            startDate = new Date();
        } else {
            if (StringUtils.isNotBlank(reqModel.startDate)) {
                reqModel.startDate = reqModel.startDate.replace("Z", " UTC");
                startDate = sdf.parse(reqModel.startDate);
            }

        }

        // 结束时间
        Integer type2 = reqModel.type2;
        Date endDate = null;
        if (type2 != null && type2 == 3) {
            endDate = getTimesnight();
        } else if (type2 != null && type2 == 6) {
            endDate = getTimesNextnight();
        } else if (type2 != null && type2 == 9) {
            endDate = getTimesWeeknight();
        } else {
            if (StringUtils.isNotBlank(reqModel.endDate)) {
                reqModel.endDate = reqModel.endDate.replace("Z", " UTC");
                endDate = sdf.parse(reqModel.endDate);
            }
        }

        Assert.isTrue(startDate.getTime() < endDate.getTime(), "截止时间不能小于开始时间");

        // 作业类型
        String content = reqModel.content;
        List<QuesModelV2> QuesModelV2List = reqModel.quesIdList;
        List<String> quesIdList = QuesModelV2List.stream().map(x -> x.quesId).collect(Collectors.toList());

        // 试题转化为map
        Map<String, List<Integer>> quesMap = QuesModelV2List.stream()
                .collect(Collectors.toMap(QuesModelV2::getQuesId, QuesModelV2::getKnow));

        // 0：试题类作业，1：通知类作业 2：阅读类作业。
        String taskType = "";
        if (CollectionUtils.isNotEmpty(quesIdList)) {
            taskType += "0";
        }
        if (CollectionUtils.isNotEmpty(reqModel.quesImages) || StringUtils.isNotBlank(content)) {
            taskType += "1";
        }
        if (CollectionUtils.isNotEmpty(reqModel.quesArticles)) {
            taskType += "2";
        }

        HomeworkTask task = new HomeworkTask();
        List<ClassModelV2> classModelList = reqModel.classModelList;
        List<String> classIdList = new ArrayList<String>();
        for (ClassModelV2 classReqModel : classModelList) {
            String classId = classReqModel.classId;
            classIdList.add(classId);
        }
        String stage = reqModel.stage;
        String subject = reqModel.subject;
        String subjectName = reqModel.subjectName;
        task.setTitle(reqModel.title);
        task.setSchoolId(schoolId);
        task.setPublishUserId(userId);
        task.setPublishUserNick(userNick);
        task.setStage(stage);
        task.setSubject(subject);
        task.setSubjectName(subjectName);
        task.setPublishAnswer(reqModel.publishAnswer);
        task.setPublishDate(startDate);
        task.setClassIds(classIdList);
        task.setPredictDate(endDate);
        task.setKnowIds(reqModel.knowIdList);
        task.setKnowNames(reqModel.knowNameList);
        task.setTaskType(taskType);
        task.setIfNeedSumbit(reqModel.ifNeedSumbit);
        task.setSource(0);
        task.setLectureType(1);
        task = taskRepository.save(task);

        List<HomeworkTaskClass> taskClassList = new ArrayList<HomeworkTaskClass>();
        HomeworkTaskClass taskClass = null;
        for (ClassModelV2 classReqModel : classModelList) {
            taskClass = new HomeworkTaskClass();
            taskClass.setTitle(task.getTitle());
            taskClass.setSubTitle(task.getSubTitle());
            taskClass.setClassId(classReqModel.classId);
            taskClass.setClassName(classReqModel.classNick);
            taskClass.setNumOfStudent(classReqModel.studentNum);
            taskClass.setGrade(classReqModel.grade);
            taskClass.setTaskId(task.getId());
            taskClass.setSchoolId(schoolId);
            taskClass.setStage(task.getStage());
            taskClass.setSubject(task.getSubject());
            taskClass.setSubjectName(task.getSubjectName());
            taskClass.setPublishDate(task.getPublishDate());
            taskClass.setPredictDate(task.getPredictDate());
            taskClass.setPublishUserId(task.getPublishUserId());
            taskClass.setPublishUserNick(task.getPublishUserNick());
            taskClass.setTaskType(task.getTaskType());
            taskClass.setSource(0);
            taskClass.setLectureType(task.getLectureType());
            taskClassList.add(taskClass);
        }
        taskClassRepository.save(taskClassList);

        // 试题类作业
        HomeworkTaskQues taskQues = null;
        HomeWorkQuesUsed quesUsed = null;
        List<HomeworkTaskQues> taskQuesList = new ArrayList<HomeworkTaskQues>();
        List<HomeWorkQuesUsed> quesUsedList = new ArrayList<HomeWorkQuesUsed>();
        int i = 1;
        for (String quesId : quesIdList) {
            quesUsed = quesUsedRepository.findByQuesId(quesId);
            if (quesUsed != null) {
                quesUsed.setUsedCount(quesUsed.getUsedCount() + 1);
            } else {
                quesUsed = new HomeWorkQuesUsed();
                quesUsed.setQuesId(quesId);
                quesUsed.setUsedCount(1l);
            }
            quesUsedList.add(quesUsed);
            // 查询试题
            ElasticYxyYxyQuesResource eQues = elasticService.findByEsQuesId(quesId);
            taskQues = new HomeworkTaskQues();
            taskQues.setTitle(task.getTitle());
            taskQues.setSubTitle(task.getSubTitle());
            taskQues.setTaskId(task.getId());
            taskQues.setPredictDate(task.getPredictDate());
            taskQues.setQuesId(quesId);
            taskQues.setTeacherId(userId);
            taskQues.setStage(reqModel.stage);
            taskQues.setSubject(reqModel.subject);
            taskQues.setOrder(i++);
            taskQues.setSource(0);
            taskQues.setLectureType(task.getLectureType());
            // 题的知识点
            List<Integer> knowIds = quesMap.get(quesId);
            taskQues.setKnowId(knowIds);// 知识点id
            // 题的知识点名称
            List<YxyQuesKnow> quesKnows = qKnowRepository.findByIdIn(knowIds);
            List<String> knowTextsList = quesKnows.stream().map(x -> x.getName()).collect(Collectors.toList());
            taskQues.setKnowName(knowTextsList);
            taskQues.setDifficultyLevel(Integer.parseInt(eQues.getDifficultyLevel()));// 难度级别
            taskQues.setDifficultyXs(eQues.getDifficultyXishu());// 难度系数
            taskQues.setTaskType(task.getTaskType());
            String questionType = eQues.getQuestionType();
            if (StringUtils.equals(questionType, "1")) {
                taskQues.setQuesType("0");
            } else if (StringUtils.equals(questionType, "8")) {
                taskQues.setQuesType("1");
            } else if (StringUtils.equals(questionType, "2")) {
                taskQues.setQuesType("3");
            } else {
                taskQues.setQuesType("4");
            }
            taskQuesList.add(taskQues);
        }
        quesUsedRepository.save(quesUsedList);

        // 通知类作业
        if (CollectionUtils.isNotEmpty(reqModel.quesImages) || StringUtils.isNotBlank(content)) {
            taskQues = new HomeworkTaskQues();
            taskQues.setTitle(task.getTitle());
            taskQues.setSubTitle(task.getSubTitle());
            taskQues.setTaskId(task.getId());
            taskQues.setPredictDate(task.getPredictDate());
            taskQues.setQuesId("tz" + UUID.randomUUID());// 生成通知类试题id
            taskQues.setQuesContent(content);
            // 通知类试题的图片
            List<Article> quesArticleList = new ArrayList<Article>();
            Article article = null;
            for (ArticleModelV2 articleReqModel : reqModel.quesImages) {
                article = new Article();
                article.setArticle_name(articleReqModel.docName);
                article.setUrl(articleReqModel.docUrl);
                quesArticleList.add(article);
            }
            taskQues.setQuesType("2");
            taskQues.setQuesArticle(quesArticleList);
            taskQues.setTeacherId(userId);
            taskQues.setStage(stage);
            taskQues.setSubject(subject);
            taskQues.setOrder(taskQuesList.size() + 1);// 通知类试题序号
            taskQues.setTaskType(task.getTaskType());
            taskQues.setIfNeedSumbit(reqModel.ifNeedSumbit);
            taskQues.setSource(0);
            taskQues.setLectureType(task.getLectureType());
            taskQuesList.add(taskQues);
        }

        // 阅读类作业
        if (CollectionUtils.isNotEmpty(reqModel.quesArticles)) {
            taskQues = new HomeworkTaskQues();
            taskQues.setTitle(task.getTitle());
            taskQues.setSubTitle(task.getSubTitle());
            taskQues.setTaskId(task.getId());
            taskQues.setPredictDate(task.getPredictDate());
            taskQues.setQuesId("yd" + UUID.randomUUID());// 生成阅读类试题id
            taskQues.setQuesContent(content);
            List<Article> quesArticleList = new ArrayList<Article>();
            Article article = null;
            for (ArticleModelV2 articleReqModel : reqModel.quesArticles) {
                article = new Article();
                article.setArticle_name(articleReqModel.docName);
                article.setUrl(articleReqModel.docUrl);
                quesArticleList.add(article);
            }
            taskQues.setQuesType("5");
            taskQues.setQuesArticle(quesArticleList);
            taskQues.setTeacherId(userId);
            taskQues.setStage(stage);
            taskQues.setSubject(subject);
            taskQues.setOrder(taskQuesList.size() + 1);// 阅读类试题序号
            taskQues.setTaskType(task.getTaskType());
            taskQues.setIfNeedSumbit(false);
            taskQues.setSource(0);
            taskQues.setLectureType(task.getLectureType());
            taskQuesList.add(taskQues);
        }

        taskQuesRepository.save(taskQuesList);

        List<HomeworkTaskReport> taskReportList = new ArrayList<HomeworkTaskReport>();
        HomeworkTaskReport taskReport = null;

        // 年度
        LocalDate localDate = LocalDate.now();
        String annual = null;
        if (localDate.getMonthValue() < 9) {
            annual = (localDate.getYear() - 1) + "";
        } else {
            annual = localDate.getYear() + "";
        }
        for (ClassModelV2 classReqModel : classModelList) {
            List<StudentModelV2> studentModelList = classReqModel.studentModelList;
            for (StudentModelV2 srudentModel : studentModelList) {
                taskReport = new HomeworkTaskReport();
                taskReport.setTaskId(task.getId());
                taskReport.setTitle(task.getTitle());
                taskReport.setSubTitle(task.getSubTitle());
                taskReport.setStudentId(srudentModel.studentId);
                taskReport.setStudentNick(srudentModel.studentName);
                taskReport.setAvatar(srudentModel.avatar);
                taskReport.setSchoolId(schoolId);
                taskReport.setClassId(classReqModel.classId);
                taskReport.setClassName(classReqModel.classNick);
                taskReport.setGrade(classReqModel.grade);
                taskReport.setAnnual(annual);
                taskReport.setStage(stage);
                taskReport.setSubject(subject);
                taskReport.setSubjectName(subjectName);
                taskReport.setPredictDate(task.getPredictDate());
                taskReport.setPublishAnswer(task.getPublishAnswer());
                taskReport.setTaskType(task.getTaskType());
                taskReport.setPublishDate(task.getPublishDate());
                taskReport.setSource(0);
                taskReport.setLectureType(task.getLectureType());
                taskReportList.add(taskReport);
            }
        }
        taskReportRepository.save(taskReportList);
        LOGGER.info("发布完成共用时:" + ((System.currentTimeMillis() - start) / 1000) + "s");
        return task;
    }
}
